﻿using System.Reflection;

namespace GMS.NET.Core.Tools
{
    /// <summary>
    /// 反射扩展
    /// </summary>
    public static class TypeTool
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values"></param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> ConvertToDictionaryList<T>(this List<T> values)
        {
            var dictionaryList = new List<Dictionary<string, object>>();

            foreach (var item in values)
            {
                var dictionary = new Dictionary<string, object>();
                var itemType = item!.GetType();
                var properties = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (var property in properties)
                {
                    var propertyName = property.Name;
                    var propertyValue = property.GetValue(item);
                    dictionary[propertyName] = propertyValue!;
                }

                dictionaryList.Add(dictionary);
            }

            return dictionaryList;
        }
        /// <summary>
        /// 判断类型是否实现某个泛型
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="generic">泛型类型</param>
        /// <returns>bool</returns>
        public static bool HasImplementedRawGeneric(this Type type, Type generic)
        {
            // 检查接口类型
            var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
            if (isTheRawGenericType) return true;

            // 检查类型
            while (type != null && type != typeof(object))
            {
                isTheRawGenericType = IsTheRawGenericType(type);
                if (isTheRawGenericType) return true;
                type = type.BaseType!;
            }

            return false;

            // 判断逻辑
            bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
        }
    }
}
